import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';

const ScreenSharing = ({ webRTCService, roomId, isRoomCreator }) => {
  const [status, setStatus] = useState(isRoomCreator ? '等待开始共享' : '等待其他用户共享屏幕');
  const [isSharing, setIsSharing] = useState(false);
  const [remoteStream, setRemoteStream] = useState(null);
  const [videoLoaded, setVideoLoaded] = useState(false);
  const [error, setError] = useState('');
  const videoRef = useRef(null);
  const localStreamRef = useRef(null);

  useEffect(() => {
    console.log('ScreenSharing: 组件挂载. 房间ID:', roomId, '是否创建者:', isRoomCreator);
    
    if (!webRTCService) {
      console.error('ScreenSharing: webRTCService 未初始化!');
      setError('WebRTC服务未初始化');
      return;
    }
    
    if (!roomId) {
      console.error('ScreenSharing: 房间ID为空!');
      setError('房间ID为空，请先加入或创建房间');
      return;
    }

    console.log('ScreenSharing: 当前WebRTC状态:', {
      socketConnected: webRTCService.socket?.connected,
      roomId: webRTCService.roomId,
      localStream: webRTCService.localStream ? 'exists' : 'null',
      peerConnections: Object.keys(webRTCService.peerConnections || {}).length
    });
    
    // 当组件挂载时请求房间状态
    if (!isRoomCreator) {
      // 短暂延迟以确保加入房间处理完成
      setTimeout(() => {
        console.log('ScreenSharing: 非创建者，在组件挂载时请求房间用户列表以检查共享状态');
        webRTCService.socket.emit('get-room-users', roomId);
      }, 1000);
    }

    // 设置接收远程流的事件监听器
    const streamReceivedCallback = (stream) => {
      console.log('ScreenSharing: 收到远程流', stream);
      setRemoteStream(stream);
      
      if (stream) {
        console.log('ScreenSharing: 远程流轨道信息:', {
          videoTracks: stream.getVideoTracks().length,
          audioTracks: stream.getAudioTracks().length,
          active: stream.active
        });
        
        if (stream.getVideoTracks().length > 0) {
          console.log('ScreenSharing: 视频轨道设置:', stream.getVideoTracks()[0].getSettings());
        }
        
        setStatus('正在接收共享屏幕');
        
        // 保存videoRef.current到变量以防回调执行时它变为null
        const videoElement = videoRef.current;
        if (videoElement) {
          videoElement.srcObject = stream;
          
          // 等待视频元数据加载，确认视频尺寸
          videoElement.onloadedmetadata = () => {
            // 再次检查videoElement是否依然有效
            if (videoElement) {
              console.log('ScreenSharing: 视频元数据已加载，尺寸:', 
                          videoElement.videoWidth, 
                          videoElement.videoHeight);
              setVideoLoaded(true);
              
              // 确保视频能播放
              videoElement.play()
                .then(() => {
                  console.log('ScreenSharing: 视频播放成功');
                })
                .catch(err => {
                  console.error('ScreenSharing: 视频播放失败:', err);
                  setError(`视频播放失败: ${err.message}`);
                });
            } else {
              console.error('ScreenSharing: 视频元素在元数据加载时已不存在');
            }
          };
        } else {
          console.error('ScreenSharing: videoRef.current 为 null，无法设置流');
          setError('视频元素未找到');
        }
      } else {
        console.log('ScreenSharing: 收到的远程流为null');
        setStatus(isRoomCreator ? '等待开始共享' : '等待其他用户共享屏幕');
        if (videoRef.current) {
          videoRef.current.srcObject = null;
        }
        setVideoLoaded(false);
      }
    };

    // 设置用户开始共享的事件监听器
    const userStartedSharingCallback = (userId) => {
      console.log(`ScreenSharing: 用户 ${userId} 开始共享屏幕`);
      if (!isRoomCreator) {
        setStatus('正在接收共享屏幕...');
      }
    };

    // 设置用户停止共享的事件监听器
    const userStoppedSharingCallback = (userId) => {
      console.log(`ScreenSharing: 用户 ${userId} 停止共享屏幕`);
      if (!isRoomCreator) {
        setStatus('等待其他用户共享屏幕');
        setVideoLoaded(false);
        
        if (videoRef.current) {
          videoRef.current.srcObject = null;
        }
      }
    };

    webRTCService.on('streamReceived', streamReceivedCallback);
    webRTCService.on('userStartedSharing', userStartedSharingCallback);
    webRTCService.on('userStoppedSharing', userStoppedSharingCallback);

    // 在组件卸载时清理事件监听器
    return () => {
      console.log('ScreenSharing: 组件卸载，清理事件监听器');
      webRTCService.off('streamReceived', streamReceivedCallback);
      webRTCService.off('userStartedSharing', userStartedSharingCallback);
      webRTCService.off('userStoppedSharing', userStoppedSharingCallback);
      stopSharing();
    };
  // eslint-disable-next-line
  }, [roomId]);

  // 开始屏幕共享
  const startSharing = async () => {
    console.log('ScreenSharing: 尝试开始屏幕共享');
    
    if (!webRTCService) {
      const errorMsg = 'WebRTC服务未初始化';
      console.error('ScreenSharing:', errorMsg);
      setError(errorMsg);
      return;
    }
    
    if (!roomId) {
      const errorMsg = '房间ID为空，请先加入或创建房间';
      console.error('ScreenSharing:', errorMsg);
      setError(errorMsg);
      return;
    }
    
    try {
      console.log('ScreenSharing: 请求屏幕共享权限');
      setStatus('正在请求屏幕共享权限...');
      setError('');
      
      // 获取屏幕共享流
      const stream = await navigator.mediaDevices.getDisplayMedia({
        video: {
          cursor: 'always',
          displaySurface: 'monitor',
        },
        audio: false
      });
      
      console.log('ScreenSharing: 获取屏幕共享流成功', stream);
      console.log('ScreenSharing: 视频轨道数量:', stream.getVideoTracks().length);
      if (stream.getVideoTracks().length > 0) {
        console.log('ScreenSharing: 视频轨道设置:', stream.getVideoTracks()[0].getSettings());
      }
      
      localStreamRef.current = stream;
      
      // 显示本地流
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        setVideoLoaded(true);
      } else {
        console.error('ScreenSharing: videoRef.current 为 null');
        setError('视频元素未找到');
        return;
      }
      
      // 开始通过WebRTC共享
      await webRTCService.startSharing(stream);
      setIsSharing(true);
      setStatus('正在共享屏幕');
      
      // 监听轨道结束事件
      stream.getVideoTracks()[0].addEventListener('ended', () => {
        console.log('ScreenSharing: 用户停止了屏幕共享');
        stopSharing();
      });
      
    } catch (err) {
      console.error('ScreenSharing: 开始屏幕共享失败:', err);
      setStatus('屏幕共享失败');
      setError(`屏幕共享失败: ${err.message}`);
      stopSharing();
    }
  };

  // 停止屏幕共享
  const stopSharing = () => {
    console.log('ScreenSharing: 停止屏幕共享');
    
    if (localStreamRef.current) {
      console.log('ScreenSharing: 停止本地媒体流轨道');
      localStreamRef.current.getTracks().forEach(track => {
        track.stop();
      });
      localStreamRef.current = null;
    }
    
    if (webRTCService && isSharing) {
      console.log('ScreenSharing: 通知WebRTC服务停止共享');
      webRTCService.stopSharing();
    }
    
    setIsSharing(false);
    setStatus(isRoomCreator ? '等待开始共享' : '等待其他用户共享屏幕');
    
    // 清除视频元素的srcObject
    if (videoRef.current) {
      videoRef.current.srcObject = null;
    }
    setVideoLoaded(false);
  };
  
  // 强制检查和播放视频
  const forcePlay = () => {
    if (!videoRef.current) {
      console.error('ScreenSharing: videoRef.current 为 null');
      setError('视频元素未找到');
      return;
    }
    
    const videoElement = videoRef.current;
    if (videoElement.srcObject) {
      console.log('ScreenSharing: 尝试强制播放视频');
      videoElement.play()
        .then(() => {
          console.log('ScreenSharing: 强制播放成功');
          setVideoLoaded(true);
        })
        .catch(err => {
          console.error('ScreenSharing: 强制播放失败:', err);
          setError(`强制播放失败: ${err.message}`);
        });
    } else {
      console.error('ScreenSharing: 视频元素没有srcObject，无法播放');
      setError('没有可播放的视频流');
    }
  };
  
  // 检查视频尺寸和状态
  const showVideoDimensions = () => {
    const videoElement = videoRef.current;
    
    if (!videoElement) {
      console.error('ScreenSharing: videoRef.current 为 null');
      setError('视频元素未找到');
      return;
    }
    
    const info = {
      videoWidth: videoElement.videoWidth || '未知',
      videoHeight: videoElement.videoHeight || '未知',
      readyState: videoElement.readyState,
      played: videoElement.played.length > 0,
      paused: videoElement.paused,
      ended: videoElement.ended,
      hasSrcObject: !!videoElement.srcObject,
      streamActive: videoElement.srcObject ? videoElement.srcObject.active : false,
      streamVideoTracks: videoElement.srcObject ? 
        videoElement.srcObject.getVideoTracks().length : 0
    };
    
    console.log('ScreenSharing: 视频信息:', info);
    alert(`视频状态:
尺寸: ${info.videoWidth}x${info.videoHeight}
就绪状态: ${info.readyState}/4
已播放: ${info.played ? '是' : '否'}
已暂停: ${info.paused ? '是' : '否'}
已结束: ${info.ended ? '是' : '否'}
有流对象: ${info.hasSrcObject ? '是' : '否'}
流是否活跃: ${info.streamActive ? '是' : '否'}
视频轨道数: ${info.streamVideoTracks}
    `);
  };
  
  // 尝试重新连接
  const attemptReconnect = async () => {
    console.log('ScreenSharing: 尝试重新连接');
    
    if (!webRTCService) {
      console.error('ScreenSharing: webRTCService 未初始化!');
      setError('WebRTC服务未初始化');
      return;
    }
    
    if (!roomId) {
      console.error('ScreenSharing: 房间ID为空!');
      setError('房间ID为空，请先加入或创建房间');
      return;
    }
    
    // 重新检查WebRTC状态
    console.log('ScreenSharing: 重连前WebRTC状态:', {
      socketConnected: webRTCService.socket?.connected,
      roomId: webRTCService.roomId,
      localStream: webRTCService.localStream ? 'exists' : 'null',
      peerConnections: Object.keys(webRTCService.peerConnections || {}).length
    });
    
    setStatus('正在尝试重新连接...');
    
    try {
      // 首先尝试使用新的reinitializeRoom方法
      await webRTCService.reinitializeRoom();
      console.log('ScreenSharing: 房间连接已重新初始化');
      
      // 基于角色的重连逻辑
      if (isRoomCreator) {
        console.log('ScreenSharing: 作为房间创建者重新连接');
        // 如果当前正在共享，尝试重新开始共享
        if (isSharing) {
          stopSharing();
          setTimeout(() => {
            console.log('ScreenSharing: 延迟1秒后重新开始共享');
            startSharing();
          }, 1000);
        } else {
          // 如果没有共享，添加日志
          console.log('ScreenSharing: 房间创建者未共享，无需重新启动共享');
          setStatus('已重新连接，等待开始共享');
        }
      } else {
        console.log('ScreenSharing: 作为观看者重新连接');
        // 观看者只需要等待远程流
        setStatus('已重新连接，等待共享画面...');
      }
    } catch (err) {
      console.error('ScreenSharing: 重新连接失败:', err);
      setError(`重新连接失败: ${err.message}`);
      
      // 如果使用新方法失败，回退到旧的重连逻辑
      if (isRoomCreator) {
        // 如果当前正在共享，尝试重新开始共享
        if (isSharing) {
          stopSharing();
          setTimeout(() => {
            console.log('ScreenSharing: 延迟1秒后重新开始共享');
            startSharing();
          }, 1000);
        } else {
          // 如果没有共享，重新加入房间
          webRTCService.leaveRoom();
          setTimeout(() => {
            console.log('ScreenSharing: 重新创建房间');
            webRTCService.createRoom(roomId);
          }, 1000);
        }
      } else {
        // 观看者重新加入房间
        webRTCService.leaveRoom();
        setTimeout(() => {
          console.log('ScreenSharing: 重新加入房间');
          webRTCService.joinRoom(roomId);
        }, 1000);
      }
    }
  };

  return (
    <div className="screen-sharing">
      {isRoomCreator ? (
        <div className="sharing-controls">
          <button 
            onClick={isSharing ? stopSharing : startSharing}
            className={`btn ${isSharing ? 'danger' : 'primary'}`}
            disabled={!roomId}
          >
            {isSharing ? '停止共享' : '开始共享'}
          </button>
          {!roomId && <p>请先创建或加入房间</p>}
        </div>
      ) : (
        <div className="viewing-info">
          <p>您是观看方，等待其他用户共享屏幕</p>
        </div>
      )}

      <div className="video-container">
        <h2>{status}</h2>
        {error && <p className="error-message">错误: {error}</p>}
        <video 
          ref={videoRef} 
          autoPlay 
          playsInline
          style={{ 
            width: '100%', 
            maxHeight: '70vh', 
            background: '#000',
            display: 'block',
            objectFit: 'contain',
            border: videoLoaded ? '2px solid green' : '1px solid #333'
          }}
          onError={(e) => {
            console.error('ScreenSharing: 视频元素错误:', e);
            setError(`视频错误: ${e.target.error?.message || '未知错误'}`);
          }}
        ></video>
        
        {/* 调试按钮组 */}
        <div className="debug-controls" style={{ marginTop: '10px', display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          <button 
            onClick={showVideoDimensions} 
            className="btn secondary"
            style={{ fontSize: '12px', padding: '5px 10px' }}
          >
            检查视频状态
          </button>
          <button 
            onClick={forcePlay} 
            className="btn primary"
            style={{ fontSize: '12px', padding: '5px 10px' }}
            disabled={!remoteStream && !isSharing}
          >
            强制播放
          </button>
          <button 
            onClick={attemptReconnect} 
            className="btn warning"
            style={{ fontSize: '12px', padding: '5px 10px' }}
          >
            重新连接
          </button>
          <span style={{ fontSize: '12px', padding: '5px', color: '#666' }}>
            视频状态: {videoLoaded ? '已加载' : '未加载'}
          </span>
        </div>
        
        {/* 连接状态信息 */}
        <div className="connection-info" style={{ 
          marginTop: '15px', 
          fontSize: '12px', 
          padding: '8px', 
          backgroundColor: '#f5f5f5', 
          borderRadius: '4px' 
        }}>
          <div><strong>房间ID:</strong> {roomId || '未加入房间'}</div>
          <div><strong>角色:</strong> {isRoomCreator ? '共享方' : '观看方'}</div>
          <div><strong>共享状态:</strong> {isSharing ? '正在共享' : '未共享'}</div>
          <div><strong>远程流:</strong> {remoteStream ? (remoteStream.active ? '活跃' : '非活跃') : '无'}</div>
          <div><strong>视频轨道:</strong> {remoteStream && remoteStream.getVideoTracks().length > 0 ? 
            `${remoteStream.getVideoTracks().length}个 (${remoteStream.getVideoTracks()[0].enabled ? '已启用' : '已禁用'})` 
            : '无'}</div>
        </div>
      </div>
    </div>
  );
};

ScreenSharing.propTypes = {
  webRTCService: PropTypes.object.isRequired,
  roomId: PropTypes.string.isRequired,
  isRoomCreator: PropTypes.bool.isRequired
};

export default ScreenSharing; 